package com.simple.microservices.commons.utils;

import com.simple.microservices.commons.constant.LoginConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 从请求头中获取参数
 * @author HYF
 */
public class CommonRequestUtils {
    private static Logger logger = LoggerFactory.getLogger(CommonRequestUtils.class);



    /**
     * 获取 设备
     *
     * @return
     */
    public static String getDevice() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        if (requestAttributes != null) {
            HttpServletRequest request = requestAttributes.getRequest();
            String device = request.getHeader(LoginConstant.EQUIPMENT_TYPE);
            logger.info("当前设备 ={}",device);
            return device;
        }

        return LoginConstant.ANDROID;
    }

    /**
     * 获取用户ID
     *
     * @return
     */
    public static String getId() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        if (requestAttributes != null) {
            HttpServletRequest request = requestAttributes.getRequest();
            String userId = request.getHeader(LoginConstant.USER_ID);
            String token = request.getHeader(LoginConstant.TOKEN);
            logger.info("获取用户ID={}", userId);
            logger.info("获取用户token={}", token);
            logger.info("获取用户URL={}", request.getRequestURI());
            return userId;
        }
        return null;
//
    }

    /**
     * 获取用户身份
     *
     * @return
     */
    public static String getIdentity() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        if (requestAttributes != null) {
            HttpServletRequest request = requestAttributes.getRequest();
            String identity = request.getHeader(LoginConstant.IDENTITY);
            logger.info("获取用户身份={}", identity);
            return identity;
        }
        return null;
    }
}
